package com.lq.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.lq.bean.EquipmentUniqueBo;
import com.lq.common.Constants;
import com.lq.common.SqlConstant;
import com.lq.utils.CommonUtil;
import com.lq.utils.jdbc.Jdbc;
import com.lq.utils.jdbc.LqJdbcFactory;
import com.lq.utils.jdbc.LqPiLiang;
import com.lq.utils.jdbc.LqShiWu;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class DataDao {

    public static Logger logger = Logger.getLogger(DataDao.class);

    public static Logger realTime = Logger.getLogger("realtime");
    public static Logger logHost = Logger.getLogger("host");
    public static Logger logDevice = Logger.getLogger("device");
    public static Logger logFloor = Logger.getLogger("floor");
    public static Logger logRecord = Logger.getLogger("record");
    public static Logger logGps = Logger.getLogger("gps");
    public static Logger logEvents = Logger.getLogger("events");
    public static Logger logCXRecord = Logger.getLogger("cxrecord");
    public static Logger logTask = Logger.getLogger("task");
    public static Logger logRepalr = Logger.getLogger("repalr");
    public static Logger logTrack = Logger.getLogger("track");
    public static Logger logRecordE = Logger.getLogger("recordE");
    public static Logger logCXRecordE = Logger.getLogger("cxrecordE");
    public static Logger logGpsE = Logger.getLogger("gpsE");

    /**
     * 设备历史数据
     *
     * @param recordArray
     * @param mapCompany
     * @param companyKey
     */
    public static void insertRecord(JSONArray recordArray, Map<String, ListOrderedMap> mapCompany, String companyKey) {
        int result = 0;
        List<Object[]> listRecord = new ArrayList();
        logRecord.info("========================================== Start ==========================================");
        if (recordArray != null && recordArray.size() > 0) {
            String recordId = "";
            try {
                for (int i = 0; i < recordArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) recordArray.get(i);
                    recordId = jsonObject.getString("id");

                    String companyCode = jsonObject.getString("companycode");
                    String areaCode = jsonObject.getString("areacode");
                    String ipAddr = jsonObject.getString("ipaddr");
                    String wdz = jsonObject.getString("wdz");
                    String sdz = jsonObject.getString("sdz");
                    //处理一下为空的数据
                    if (StringUtils.isEmpty(sdz)) {
                        sdz = "1101";
                    }
                    String dt = jsonObject.getString("dt");
                    String GPSJD = jsonObject.getString("gpsjd");
                    String GPSWD = jsonObject.getString("gpswd");
                    String deviceSnHex10 = jsonObject.getString("devid");
                    String deviceSnHex16 = jsonObject.getString("devidinside");
                    String SJWDZ = jsonObject.getString("sjwdz");
                    String SJSDZ = jsonObject.getString("sjsdz");
                    String Tasks = jsonObject.getString("tasks");
                    String DevHostID = jsonObject.getString("devhostid");
                    String TypeNumber = jsonObject.getString("typenumber");
                    String OverLimitMark = jsonObject.getString("overlimitmark");
                    if (mapCompany.containsKey(companyCode)) {
                        Object[] obj = new Object[]{companyCode, areaCode, ipAddr, wdz, sdz, dt, GPSJD, GPSWD, OverLimitMark, TypeNumber, deviceSnHex10, deviceSnHex16, DevHostID};
                        listRecord.add(obj);
                    }
                }
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(SqlConstant.SQL_INSERT_RECORD, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listRecord.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                logRecord.info("==> 历史温湿度数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
                logRecord.info("==> 历史温湿度数据，插入节点===========》【" + recordId + "】");
                updateTrackPingTai(companyKey, recordId, Constants.COLL_NAME_RECORD);
            } catch (Exception e) {
                logRecord.info("==> 历史温湿度数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logRecord.info("==> 暂无需要插入的数据,说明没有数据返回");
        }
        logRecord.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 设备超限数据
     *
     * @param XRecordArray
     * @param mapCompany
     * @param companyKey
     */
    public static void insertXRecord(JSONArray XRecordArray, Map<String, ListOrderedMap> mapCompany, String companyKey) {
        int result = 0;
        List<Object[]> listXRecord = new ArrayList();
        logCXRecord.info("========================================== Start ==========================================");
        if (XRecordArray != null && XRecordArray.size() > 0) {
            String XRecordId = "";
            try {
                for (int i = 0; i < XRecordArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) XRecordArray.get(i);
                    XRecordId = jsonObject.getString("id");

                    String companyCode = jsonObject.getString("companycode");
                    String areaCode = jsonObject.getString("areacode");
                    String ipAddr = jsonObject.getString("ipaddr");
                    String wdz = jsonObject.getString("wdz");
                    String sdz = jsonObject.getString("sdz");
                    String dt = jsonObject.getString("dt");
                    //温度报警上限
                    String wdbjsx = jsonObject.get("wdbjsx").toString();
                    String WDBJSX = StringUtils.isNotBlank(wdbjsx) && !"null".equals(wdbjsx) ? wdbjsx : null;
                    //温度报警下限
                    String wdbjxx = jsonObject.get("wdbjxx").toString();
                    String WDBJXX = StringUtils.isNotBlank(wdbjxx) && !"null".equals(wdbjxx) ? wdbjxx : null;

                    //温度预警上限
                    String wdyjsx = jsonObject.get("wdyjsx").toString();
                    String WDYJSX = StringUtils.isNotBlank(wdyjsx) && !"null".equals(wdyjsx) ? wdyjsx : null;
                    //温度预警下限
                    String wdyjxx = jsonObject.get("wdyjxx").toString();
                    String WDYJXX = StringUtils.isNotBlank(wdyjxx) && !"null".equals(wdyjxx) ? wdyjxx : null;
                    //湿度报警上限
                    String sdbjsx = jsonObject.get("sdbjsx").toString();
                    String SDBJSX = StringUtils.isNotBlank(sdbjsx) && !"null".equals(sdbjsx) ? sdbjsx : null;
                    //湿度报警下限
                    String sdbjxx = jsonObject.get("sdbjxx").toString();
                    String SDBJXX = StringUtils.isNotBlank(sdbjxx) && !"null".equals(sdbjxx) ? sdbjxx : null;
                    //湿度预警上限
                    String sdyjsx = jsonObject.get("sdyjsx").toString();
                    String SDYJSX = StringUtils.isNotBlank(sdyjsx) && !"null".equals(sdyjsx) ? sdyjsx : null;
                    //湿度预警下限
                    String sdyjxx = jsonObject.get("sdyjxx").toString();
                    String SDYJXX = StringUtils.isNotBlank(sdyjxx) && !"null".equals(sdyjxx) ? sdyjxx : null;
                    //经纬度
                    String GPSJD = jsonObject.getString("gpsjd");
                    String GPSWD = jsonObject.getString("gpswd");
                    //备注信息s
                    String Remark = jsonObject.getString("remark");
                    //设备序列号
                    String deviceSnHex10 = jsonObject.getString("devid");
                    String deviceSnHex16 = jsonObject.getString("devidinside");
                    //设备主机序列号
                    String DevHostID = jsonObject.getString("devhostid");
                    //编码类型
                    String TypeNumber = jsonObject.getString("typenumber");
                    if (mapCompany.containsKey(companyCode)) {
                        Object[] obj = new Object[]{companyCode, areaCode, ipAddr,
                                StringUtils.isNotBlank(WDBJSX) ? WDBJSX : null,
                                StringUtils.isNotBlank(WDBJXX) ? WDBJXX : null,
                                StringUtils.isNotBlank(WDYJSX) ? WDYJSX : null,
                                StringUtils.isNotBlank(WDYJXX) ? WDYJXX : null,
                                StringUtils.isNotBlank(SDBJSX) ? SDBJSX : null,
                                StringUtils.isNotBlank(SDBJXX) ? SDBJXX : null,
                                StringUtils.isNotBlank(SDYJSX) ? SDYJSX : null,
                                StringUtils.isNotBlank(SDYJXX) ? SDYJXX : null,
                                wdz, sdz, GPSJD, GPSWD, dt, Remark, TypeNumber, deviceSnHex10, deviceSnHex16, DevHostID};
                        listXRecord.add(obj);
                    }
                }
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(SqlConstant.SQL_INSERT_RECORD_ALARMS, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listXRecord.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                logCXRecord.info("==> 超限温湿度数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
                logCXRecord.info("==> 超限温湿度数据，插入节点===========》【" + XRecordId + "】");
                updateTrackPingTai(companyKey, XRecordId, Constants.COLL_NAME_RECORD_ALARMS);
            } catch (Exception e) {
                logCXRecord.info("==> 超限温湿度数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logCXRecord.info("==> 超限温湿度数据，暂无需要插入的数据，说明没有数据返回");
        }
        logCXRecord.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 设备定位数据
     *
     * @param gpsArray
     * @param mapCompany
     * @param companyKey
     */
    public static void insertGps(JSONArray gpsArray, Map<String, ListOrderedMap> mapCompany, String companyKey) {
        int result = 0;
        List<Object[]> listGps = new ArrayList();
        logGps.info("========================================== Start ==========================================");
        if (gpsArray != null && gpsArray.size() > 0) {
            String gpsId = "";
            try {
                List<Map<String, Object[]>> dataMapList = new ArrayList<>();
                for (int i = 0; i < gpsArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) gpsArray.get(i);
                    gpsId = jsonObject.getString("id");
                    String companyCode = jsonObject.getString("companycode");
                    String areaCode = jsonObject.getString("areacode");
                    String ipAddr = jsonObject.getString("ipaddr");
                    String jd = jsonObject.getString("jd");
                    String wd = jsonObject.getString("wd");
                    String dt = jsonObject.getString("dt");
                    String DevID = jsonObject.getString("devid");
                    String DevHostID = jsonObject.getString("devhostid");
                    String TypeNumber = jsonObject.getString("typenumber");
                    if (mapCompany.containsKey(companyCode)) {
                        Object[] obj = new Object[]{companyCode, areaCode, ipAddr, dt, jd, wd, TypeNumber, DevID, DevHostID};
                        listGps.add(obj);

                        //存放主机定位数据
                        Map<String, Object[]> dataMap = new HashMap();
                        dataMap.put(DevHostID, new Object[]{DevHostID, companyCode, areaCode, jd, wd, dt, TypeNumber, companyCode, areaCode, jd, wd, dt, TypeNumber});
                        dataMapList.add(dataMap);
                    }
                }
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(SqlConstant.SQL_INSERT_GPS, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listGps.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                //电子围栏主机定位数据
                List<Object[]> listFenceHostGps = new ArrayList<>();
                for (int i = 0; i < dataMapList.size(); i++) {
                    Map<String, Object[]> map = dataMapList.get(i);
                    for (Object key : map.keySet()) {
                        listFenceHostGps.add(map.get(key));
                    }
                }
                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_FENCE_HOST_GPS, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listFenceHostGps.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                logGps.info("==> 定位数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
                logGps.info("==> 定位数据，插入节点===========》【" + gpsId + "】");
                updateTrackPingTai(companyKey, gpsId, Constants.COLL_NAME_GPS);
            } catch (Exception e) {
                logGps.info("定位数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logGps.info("==> 定位数据，暂无需要插入的数据，说明没有数据返回");
        }
        logGps.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 设备事件数据
     *
     * @param gpsArray
     * @param mapCompany
     * @param companyKey
     */
    public static void insertEvents(JSONArray gpsArray, Map<String, ListOrderedMap> mapCompany, String companyKey) {
        int result = 0;
        List<Object[]> listEvents = new ArrayList();
        logEvents.info("========================================== Start ==========================================");
        if (gpsArray != null && gpsArray.size() > 0) {
            String eventsId = "";
            try {
                for (int i = 0; i < gpsArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) gpsArray.get(i);
                    eventsId = jsonObject.getString("id");
                    String companyCode = jsonObject.getString("companycode");
                    String areaCode = jsonObject.getString("areacode");
                    String ipAddr = jsonObject.getString("ipaddr");
                    String wdz = jsonObject.getString("wdz");
                    String sdz = jsonObject.getString("sdz");
                    String dt = jsonObject.getString("dt");
                    String DevID = jsonObject.getString("devid");
                    String DevIDInside = jsonObject.getString("devidinside");
                    String DevHostID = jsonObject.getString("devhostid");
                    String EventType = jsonObject.getString("eventtype");
                    String AlarmValue = jsonObject.getString("alarmvalue");
                    String Content = jsonObject.getString("content");
                    String TypeNumber = jsonObject.getString("typenumber");
                    String OverLimitMark = jsonObject.getString("overlimitmark");
                    if (mapCompany.containsKey(companyCode)) {
                        Object[] obj = new Object[]{companyCode, areaCode, ipAddr, wdz, sdz, dt, Content, EventType, OverLimitMark, AlarmValue, DevID, DevIDInside, DevHostID, Constants.PUSH_TYPE};
                        listEvents.add(obj);
                    }
                }
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(SqlConstant.SQL_INSERT_EVENTS, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listEvents.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                logEvents.info("==> 定位数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
                logEvents.info("==> 定位数据，插入节点===========》【" + eventsId + "】");
                updateTrackPingTai(companyKey, eventsId, Constants.COLL_NAME_EVENTS);
            } catch (Exception e) {
                logEvents.info("定位数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logEvents.info("==> 定位数据，暂无需要插入的数据，说明没有数据返回");
        }
        logEvents.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 任务日志数据
     *
     * @param recordTaskArray
     * @param mapCompany
     * @param companyKey
     */
    public static void insertRecordTask(JSONArray recordTaskArray, Map<String, ListOrderedMap> mapCompany, String companyKey) {
        int result = 0;
        List<Object[]> listRecordTask = new ArrayList();
        logTask.info("========================================== Start ==========================================");
        if (recordTaskArray != null && recordTaskArray.size() > 0) {
            String TaskId = "";
            try {
                for (int i = 0; i < recordTaskArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) recordTaskArray.get(i);
                    TaskId = jsonObject.getString("id");

                    String companyCode = jsonObject.getString("companycode");
                    String areaCode = jsonObject.getString("areacode");
                    String deviceHostId = jsonObject.getString("devicehostid");
                    String taskNum = jsonObject.getString("tasknum");
                    String dtStart = jsonObject.getString("dtstart");
                    String dtEnd = jsonObject.getString("dtend");
                    String typeNumber = jsonObject.getString("typenumber");
                    if (mapCompany.containsKey(companyCode)) {
                        Object[] obj = new Object[]{companyCode, areaCode, deviceHostId, taskNum, dtStart, dtEnd, typeNumber};
                        listRecordTask.add(obj);
                    }
                }
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(SqlConstant.SQL_INSERT_RECORD_TASK, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        listRecordTask.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                logTask.info("==> 设备任务日志数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
                logTask.info("==> 设备任务日志数据，插入节点===========》【" + TaskId + "】");
                updateTrackPingTai(companyKey, TaskId, Constants.COLL_NAME_RECORD_TASK);
            } catch (Exception e) {
                logTask.info("==> 设备任务日志数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logTask.info("==> 设备任务日志数据，暂无需要插入的数据，说明没有数据返回");
        }
        logTask.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 设备报修数据
     *
     * @param repalrArray
     */
    public static void insertRepalr(JSONArray repalrArray) {
        int result = 0;
        List<Object[]> insertList = new ArrayList<>();
        logRepalr.info("========================================== Start ==========================================");
        if (repalrArray != null && repalrArray.size() > 0) {
            try {
                for (int i = 0; i < repalrArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) repalrArray.get(i);
                    Object[] obj = new Object[]{jsonObject.getString("device_host_id"), jsonObject.getString("company_code"), jsonObject.getString("repalr_time")};
                    insertList.add(obj);
                }
                String sql = "insert ignore into repalr_data ( device_host_id, company_code, repalr_time) values (?, ?, ?) ";
                //批量插入数据
                int[] piliangResult = Jdbc.piliang(sql, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        insertList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                if (piliangResult != null) {
                    result = 1;
                }
                logRepalr.info("==> 设备报修数据，插入状态===========》【" + (result > 0 ? "成功" : "失败") + "】");
            } catch (Exception e) {
                logRepalr.info("设备报修数据，插入异常===========》" + Constants.LINE_SEPARATOR + CommonUtil.e(e));
                e.printStackTrace();
            }
        } else {
            logRepalr.info("==> 设备报修数据，暂无需要插入的数据，说明没有数据返回");
        }
        logRepalr.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }


    /**
     * 测点设备数据
     *
     * @param jsonArray
     */
    public static void insertEquipment(JSONArray jsonArray) {
        List<Object[]> insertList = new ArrayList<>();
        List<Object[]> updateList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject pointJson = jsonArray.getJSONObject(i);
            String companyCode = pointJson.get("company_code").toString();
            String areaCode = pointJson.get("area_code").toString();
            String deviceHostId = pointJson.get("device_host_id").toString();
            String deviceId = pointJson.get("device_id").toString();
            String deviceIdInside = pointJson.get("device_id_inside").toString();
            String pointAddr = pointJson.get("measuring_point_addr").toString();
            String pointName = pointJson.get("measuring_point_name").toString();
            String storehouseProperty = pointJson.get("storehouse_property").toString();
            String equipmentNumber = pointJson.get("equipment_number").toString();
            String saveType = pointJson.get("display_type").toString();
            //温度报警上限
            String temAHL = pointJson.get("tem_alarm_high_limit") + "";
            String temAlarmHighLimit = StringUtils.isNotBlank(temAHL) && !"null".equals(temAHL) ? temAHL : null;
            //温度报警下限
            String temALL = pointJson.get("tem_alarm_lower_limit") + "";
            String temAlarmLowerLimit = StringUtils.isNotBlank(temALL) && !"null".equals(temALL) ? temALL : null;
            //温度预警上限
            String temWHL = pointJson.get("tem_warning_high_limit") + "";
            String temWarningHighLimit = StringUtils.isNotBlank(temWHL) && !"null".equals(temWHL) ? temWHL : null;
            //温度预警下限
            String temWLL = pointJson.get("tem_warning_lower_limit") + "";
            String temWarningLowerLimit = StringUtils.isNotBlank(temWLL) && !"null".equals(temWLL) ? temWLL : null;
            //湿度报警上限
            String humAHL = pointJson.get("hum_alarm_high_limit") + "";
            String humAlarmHighLimit = StringUtils.isNotBlank(humAHL) && !"null".equals(humAHL) ? humAHL : null;
            //湿度报警下限
            String humALL = pointJson.get("hum_alarm_lower_limit") + "";
            String humAlarmLowerLimit = StringUtils.isNotBlank(humALL) && !"null".equals(humALL) ? humALL : null;
            //湿度预警上限
            String humWHL = pointJson.get("hum_warning_high_limit") + "";
            String humWarningHighLimit = StringUtils.isNotBlank(humWHL) && !"null".equals(humWHL) ? humWHL : null;
            //湿度预警下限
            String humWLL = pointJson.get("hum_warning_lower_limit") + "";
            String humWarningLowerLimit = StringUtils.isNotBlank(humWLL) && !"null".equals(humWLL) ? humWLL : null;

            //判断是否存在
            StringBuffer findSb = new StringBuffer();
            findSb.append(" and device_id = '" + deviceId + "'");
            List<ListOrderedMap> checkList = Jdbc.find(SqlConstant.SQL_SELECT_CHECK_POINT_MQTT + findSb.toString(), new Object[]{});
            if (checkList != null && checkList.size() > 0) {
                Object[] updateObj = new Object[]{
                        companyCode,
                        areaCode,
                        deviceId,
                        deviceIdInside,
                        deviceHostId,
                        pointAddr, storehouseProperty,
                        temAlarmHighLimit, temAlarmLowerLimit, temWarningHighLimit, temWarningLowerLimit,
                        humAlarmHighLimit, humAlarmLowerLimit, humWarningHighLimit, humWarningLowerLimit, deviceId};
                updateList.add(updateObj);
            } else {
                Object[] insertObj = new Object[]{
                        companyCode,
                        areaCode,
                        deviceId,
                        deviceIdInside,
                        deviceHostId,
                        pointAddr,
                        pointName,
                        storehouseProperty,
                        saveType,
                        temAlarmHighLimit, temAlarmLowerLimit, temWarningHighLimit, temWarningLowerLimit,
                        humAlarmHighLimit, humAlarmLowerLimit, humWarningHighLimit, humWarningLowerLimit};
                insertList.add(insertObj);
            }
        }

        //插入
        if (insertList.size() > 0) {
            Jdbc.piliang(SqlConstant.SQL_INSERT_POINT_MQTT, new LqPiLiang() {
                public void piliang(LqJdbcFactory jdbc) {
                    insertList.forEach(l -> {
                        jdbc.executeS(l);
                    });
                }
            });
        }
        //更新
        if (updateList.size() > 0) {
            Jdbc.piliang(SqlConstant.SQL_UPDATE_POINT_MQTT, new LqPiLiang() {
                public void piliang(LqJdbcFactory jdbc) {
                    updateList.forEach(l -> {
                        jdbc.executeS(l);
                    });
                }
            });
        }
    }


    /**
     * 设备主机数据，新结构
     *
     * @param jsonArray
     */
    public static void insertManageHost(JSONArray jsonArray, String terraceType, List<ListOrderedMap> companyList) {
        List<String> upHostList = (List<String>) jsonArray.stream()
                .map(obj -> ((JSONObject) obj).getString("host_sn"))
                .collect(Collectors.toList());

        logHost.info("========================================== Start   ==========================================");
        long timeStart = System.currentTimeMillis();
        try {
            int threadNum = 1;
            if (jsonArray.size() >= 500) {
                threadNum = jsonArray.size() / 500;
            }
            ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
            CountDownLatch countDownLatch = new CountDownLatch(threadNum);
            //计算每个线程需要处理的数据量
            int chunkSize = jsonArray.size() / threadNum;
            int remainder = jsonArray.size() % threadNum;
            //启动线程
            int startIndex = 0;
            for (int i = 0; i < threadNum; i++) {
                int endIndex = startIndex + chunkSize;
                if (remainder > 0) {
                    endIndex++;
                    remainder--;
                }
                List<Object> subList = jsonArray.subList(startIndex, endIndex);
                MultiThreadHost thread = new MultiThreadHost();
                thread.setTerraceType(terraceType);
                thread.setCompanyList(companyList);
                thread.setSubList(subList);
                thread.setCountDownLatch(countDownLatch);
                executorService.submit(thread);
                startIndex = endIndex;
            }
            try {
                countDownLatch.await();
                executorService.shutdown();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long timeEnd = System.currentTimeMillis() - timeStart;
            logHost.info("========================================== 耗时： " + timeEnd + "ms ======================================");

            //删除掉不存在的主机信息
            List<ListOrderedMap> hostList = Jdbc.find("select * from manage_host where source = ? ", new Object[]{"3"});
            List<String> dbHostList = null;
            if (hostList != null && hostList.size() > 0) {
                dbHostList = hostList.stream().map(item -> item.get("host_sn").toString()).collect(Collectors.toList());
            }
            if (dbHostList != null && dbHostList.size() > 0) {
                List stringList = dbHostList.stream().filter(t -> !upHostList.contains(t)).collect(Collectors.toList());
                if (stringList != null && stringList.size() > 0) {
                    String strDifference = stringList.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(",")).toString();

                    Object[] delObj = new Object[]{"3"};
                    String delSql = "delete from manage_host where  source = ? and  host_sn in (" + strDifference + ")";
                    Jdbc.execute(delSql, delObj);
                    logHost.info(Jdbc.sqlRender(delSql, delObj).replaceAll("\r|\n", "") + ";");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logHost.info("========================================== End ==============================================" + Constants.LINE_SEPARATOR);
        }
    }


    /**
     * 分层数据信息
     *
     * @param jsonArray
     */
    public static void insertEquipmentLayered(JSONArray jsonArray) {
        logFloor.info("========================================== Start   ==========================================");
        long timeStart = System.currentTimeMillis();
        try {
            Stream<JSONObject> jsonStream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(jsonArray.iterator(), 0), false);
            Map<String, List<JSONObject>> groupList = jsonStream
                    .collect(Collectors.groupingBy(obj -> obj.getString("company_code") + "_" + obj.getString("area_code") + "_" + obj.getString("storey_id")));

            List<Object[]> floorObjList = new ArrayList<>();
            List<Object[]> floorImageObjList = new ArrayList<>();
            List<Object[]> floorPointObjList = new ArrayList<>();
            List<Object[]> mqttPointObjList = new ArrayList<>();
            List<Object[]> assemblePointObjList = new ArrayList<>();

            List<String> upFloorList = new ArrayList<>();
            List<String> upFloorPointList = new ArrayList<>();
            for (Map.Entry<String, List<JSONObject>> mapEntry : groupList.entrySet()) {
                String key = mapEntry.getKey();
                String[] keyArray = key.split("_");
                String companyCode = keyArray[0];
                String areaCode = keyArray[1];
                String storeyId = keyArray[2];

                //获取返回的数据
                upFloorList.add(storeyId);

                JSONObject floorData = mapEntry.getValue().get(0);
                //分层数据
                Object[] floorObj = new Object[]{companyCode, areaCode, storeyId, floorData.getString("storey"), floorData.getString("px"), "1", floorData.getString("storey"), floorData.getString("px"), "1"};
                floorObjList.add(floorObj);

                //分层图片
                Object[] floorImageObj = new Object[]{companyCode, areaCode, storeyId, floorData.getString("area_img"), floorData.getString("px"), "1", floorData.getString("area_img"), floorData.getString("px"), "1"};
                floorImageObjList.add(floorImageObj);

                //分层测点
                List<JSONObject> arrayList = mapEntry.getValue();
                for (int i = 0; i < arrayList.size(); i++) {
                    JSONObject jsonObject = arrayList.get(i);
                    //同步的设备信息
                    upFloorPointList.add(jsonObject.getString("device_unique"));

                    Object[] floorPoitnObj = new Object[]{
                            companyCode,
                            areaCode,
                            storeyId,
                            jsonObject.getString("device_unique"),
                            jsonObject.getString("point_addr"),
                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),
                            "measure_point_config_mqtt",

                            jsonObject.getString("point_addr"),
                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),
                            "measure_point_config_mqtt",
                    };
                    floorPointObjList.add(floorPoitnObj);

                    //设备MQTT测点表
                    Object[] mqttPointObj = new Object[]{
                            companyCode,
                            areaCode,
                            jsonObject.getString("point_addr"),
                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),

                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),
                    };
                    mqttPointObjList.add(mqttPointObj);

                    //设备汇总测点表
                    Object[] assemblePointObj = new Object[]{
                            jsonObject.getString("device_unique"),
                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),
                            "measure_point_config_mqtt",

                            jsonObject.getString("x"),
                            jsonObject.getString("y"),
                            jsonObject.getString("isshow"),
                            "measure_point_config_mqtt"
                    };
                    assemblePointObjList.add(assemblePointObj);
                }

                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_COMPANY_AREA_FLOOR, new LqPiLiang() {
                    @Override
                    public void piliang(LqJdbcFactory jdbc) {
                        floorObjList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_COMPANY_AREA_FLOOR_IMG, new LqPiLiang() {
                    @Override
                    public void piliang(LqJdbcFactory jdbc) {
                        floorImageObjList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_COMPANY_AREA_FLOOR_POINT, new LqPiLiang() {
                    @Override
                    public void piliang(LqJdbcFactory jdbc) {
                        floorPointObjList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_MQTT_POINT, new LqPiLiang() {
                    @Override
                    public void piliang(LqJdbcFactory jdbc) {
                        mqttPointObjList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
                Jdbc.piliang(SqlConstant.SQL_INSER_INTO_ASSEMBLE_POINT, new LqPiLiang() {
                    @Override
                    public void piliang(LqJdbcFactory jdbc) {
                        assemblePointObjList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });

                //删除掉分层、分层图片、分层测点
                List<ListOrderedMap> floorList = Jdbc.find("select * from company_area_floor where company_code = ? and area_code =? ", new Object[]{companyCode, areaCode});
                List<String> dbFloorList = null;
                if (floorList != null && floorList.size() > 0) {
                    dbFloorList = floorList.stream().map(item -> item.get("storey_id").toString()).collect(Collectors.toList());
                }
                if (dbFloorList != null && dbFloorList.size() > 0) {
                    List stringList = dbFloorList.stream().filter(t -> !upFloorList.contains(t)).collect(Collectors.toList());
                    if (stringList != null && stringList.size() > 0) {
                        String strDifference = stringList.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(",")).toString();

                        //删除分层数据
                        String delFloorSql = "delete from company_area_floor where  company_code = ? and area_code = ? and storey_id in (" + strDifference + ")";
                        Object[] delFloorObj = new Object[]{companyCode, areaCode};
                        //删除分层图片
                        String delFloorImgSql = "delete from company_area_floor_img where  company_code = ? and area_code =? and storey_id in (" + strDifference + ")";
                        Object[] delFloorImgObj = new Object[]{companyCode, areaCode};
                        //删除分层测点
                        String delFloorPointSql = "delete from company_area_floor_point where  company_code = ? and area_code =? and storey_id in (" + strDifference + ")";
                        Object[] delFloorPointObj = new Object[]{companyCode, areaCode};
                        Jdbc.shiwu(new LqShiWu() {
                            @Override
                            public void shiwu(LqJdbcFactory jdbc) {
                                jdbc.execute(delFloorSql, delFloorObj);
                                jdbc.execute(delFloorImgSql, delFloorImgObj);
                                jdbc.execute(delFloorPointSql, delFloorPointObj);
                            }
                        });
                    }
                }else{
                    List<ListOrderedMap> floorPointList = Jdbc.find("select * from company_area_floor where company_code = ? and area_code =? ", new Object[]{companyCode, areaCode});
                    List<String> dbFloorPointList = null;
                    if (floorPointList != null && floorPointList.size() > 0) {
                        dbFloorPointList = floorPointList.stream().map(item -> item.get("device_unique").toString()).collect(Collectors.toList());
                    }
                    if (dbFloorPointList != null && dbFloorPointList.size() > 0) {
                        List stringList = dbFloorPointList.stream().filter(t -> !upFloorPointList.contains(t)).collect(Collectors.toList());
                        if (stringList != null && stringList.size() > 0) {
                            String strDifference = stringList.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(",")).toString();

                            String delFloorPointSql = "delete from company_area_floor_point where  company_code = ? and area_code =? and device_unique in (" + strDifference + ")";
                            Object[] delFloorPointObj = new Object[]{companyCode, areaCode};
                            Jdbc.execute(delFloorPointSql, delFloorPointObj);
                        }
                    }
                }
            }
            long timeEnd = System.currentTimeMillis() - timeStart;
            logFloor.info("========================================== 耗时： " + timeEnd + "ms ======================================");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logFloor.info("========================================== End ==============================================" + Constants.LINE_SEPARATOR);
        }
    }


    /**
     * 设备测点数据，新结构
     *
     * @param jsonArray
     */
    public static void insertEquipmentInfo(JSONArray jsonArray, String companys, String terraceType, List<ListOrderedMap> companyList) {
        List<String> upPointList = (List<String>) jsonArray.stream()
                .map(obj -> ((JSONObject) obj).getString("sn"))
                .collect(Collectors.toList());

        logDevice.info("========================================== Start   ==========================================");
        long timeStart = System.currentTimeMillis();
        try {
            int threadNum = 1;
            if (jsonArray.size() >= 500) {
                threadNum = jsonArray.size() / 500;
            }
            ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
            CountDownLatch countDownLatch = new CountDownLatch(threadNum);
            //计算每个线程需要处理的数据量
            int chunkSize = jsonArray.size() / threadNum;
            int remainder = jsonArray.size() % threadNum;
            //启动线程
            int startIndex = 0;
            for (int i = 0; i < threadNum; i++) {
                int endIndex = startIndex + chunkSize;
                if (remainder > 0) {
                    endIndex++;
                    remainder--;
                }
                List<Object> subList = jsonArray.subList(startIndex, endIndex);
                MultiThreadPoint thread = new MultiThreadPoint();
                thread.setTerraceType(terraceType);
                thread.setCompanyList(companyList);
                thread.setSubList(subList);
                thread.setCountDownLatch(countDownLatch);
                executorService.submit(thread);
                startIndex = endIndex;
            }
            try {
                countDownLatch.await();
                executorService.shutdown();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long timeEnd = System.currentTimeMillis() - timeStart;
            logDevice.info("========================================== 耗时： " + timeEnd + "ms ======================================");

            //删除掉不存在的测点信息
            List<ListOrderedMap> pointList = Jdbc.find("select * from measure_point_config_mqtt where company_code in (" + companys + ") ", new Object[]{});
            List<String> dbPointList = null;
            if (pointList != null && pointList.size() > 0) {
                dbPointList = pointList.stream().map(item -> item.get("device_id_inside").toString()).collect(Collectors.toList());
            }
            if (dbPointList != null && dbPointList.size() > 0) {
                List stringList = dbPointList.stream().filter(t -> !upPointList.contains(t)).collect(Collectors.toList());
                if (stringList != null && stringList.size() > 0) {
                    String strDifference = stringList.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(",")).toString();

                    String delSql = "delete from measure_point_config_mqtt where device_id_inside in (" + strDifference + ")";
                    int result = Jdbc.execute(delSql);
                    logDevice.info(" 【" + (result > 0 ? "成功" : "失败") + "】 " + delSql);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logDevice.info("========================================== End ==============================================" + Constants.LINE_SEPARATOR);
        }
    }


    /**
     * 设备唯一标识
     *
     * @param jsonArray
     */
    public static void insertEquipmentUnique(JSONArray jsonArray) {
        try {
            List<Object[]> insertList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String uniqueNumber = jsonObject.getString("unique_number");
                String uniqueName = jsonObject.getString("unique_name");
                String storehouseProperty = jsonObject.getString("storehouse_property");
                String paramJump = jsonObject.getString("param_jump");
                String sensor = jsonObject.getString("sensor");
                String displayType = jsonObject.getString("display_type");
                String isPointAddr = jsonObject.getString("is_point_addr");
                String isPointName = jsonObject.getString("is_point_name");
                String isHostNumber = jsonObject.getString("is_host_number");
                String isConsistent = jsonObject.getString("is_consistent");
                String bindingType = jsonObject.getString("binding_type");
                String monitoringType = jsonObject.getString("monitoring_type");
                String isLocation = jsonObject.getString("is_location");
                //温度报警上限
                String temAHL = jsonObject.get("tem_alarm_high_limit") + "";
                String temAlarmHighLimit = StringUtils.isNotBlank(temAHL) && !"null".equals(temAHL) ? temAHL : null;
                //温度报警下限
                String temALL = jsonObject.get("tem_alarm_lower_limit") + "";
                String temAlarmLowerLimit = StringUtils.isNotBlank(temALL) && !"null".equals(temALL) ? temALL : null;
                //温度预警上限
                String temWHL = jsonObject.get("tem_warning_high_limit") + "";
                String temWarningHighLimit = StringUtils.isNotBlank(temWHL) && !"null".equals(temWHL) ? temWHL : null;
                //温度预警下限
                String temWLL = jsonObject.get("tem_warning_lower_limit") + "";
                String temWarningLowerLimit = StringUtils.isNotBlank(temWLL) && !"null".equals(temWLL) ? temWLL : null;
                //湿度报警上限
                String humAHL = jsonObject.get("hum_alarm_high_limit") + "";
                String humAlarmHighLimit = StringUtils.isNotBlank(humAHL) && !"null".equals(humAHL) ? humAHL : null;
                //湿度报警下限
                String humALL = jsonObject.get("hum_alarm_lower_limit") + "";
                String humAlarmLowerLimit = StringUtils.isNotBlank(humALL) && !"null".equals(humALL) ? humALL : null;
                //湿度预警上限
                String humWHL = jsonObject.get("hum_warning_high_limit") + "";
                String humWarningHighLimit = StringUtils.isNotBlank(humWHL) && !"null".equals(humWHL) ? humWHL : null;
                //湿度预警下限
                String humWLL = jsonObject.get("hum_warning_lower_limit") + "";
                String humWarningLowerLimit = StringUtils.isNotBlank(humWLL) && !"null".equals(humWLL) ? humWLL : null;
                Object[] insertObj = new Object[]{
                        uniqueNumber,
                        uniqueName,
                        storehouseProperty,
                        paramJump,
                        sensor,
                        displayType,
                        isPointAddr,
                        isPointName,
                        isHostNumber,
                        isConsistent,
                        isLocation,
                        bindingType,
                        monitoringType,
                        temAlarmHighLimit, temAlarmLowerLimit, temWarningHighLimit, temWarningLowerLimit,
                        humAlarmHighLimit, humAlarmLowerLimit, humWarningHighLimit, humWarningLowerLimit,

                        uniqueName,
                        storehouseProperty,
                        paramJump,
                        sensor,
                        displayType,
                        isPointAddr,
                        isPointName,
                        isHostNumber,
                        isConsistent,
                        isLocation,
                        bindingType,
                        monitoringType,
                        temAlarmHighLimit, temAlarmLowerLimit, temWarningHighLimit, temWarningLowerLimit,
                        humAlarmHighLimit, humAlarmLowerLimit, humWarningHighLimit, humWarningLowerLimit,
                };
                insertList.add(insertObj);
            }
            if (insertList.size() > 0) {
                Jdbc.piliang(SqlConstant.SQL_REPLACE_INTO_EQUIPMENT_UNIQUE, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        insertList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存实时数据（专用甘肃红十字血液中心）
     *
     * @param jsonArray
     * @param companyCode
     * @param areaCode
     */
    public static void insertRealTimeData(JSONArray jsonArray, String companyCode, String areaCode) {
        try {
            List<EquipmentUniqueBo> uniqueList = Jdbc.find("select * from equipment_unique", EquipmentUniqueBo.class, new Object[]{});
            Map<String, EquipmentUniqueBo> uniqueMap = uniqueList.stream().collect(Collectors.toMap(EquipmentUniqueBo::getUniqueNumber, obj -> obj, (key1, key2) -> key1));

            String insertRealTimeSQL = "replace into real_time_socket " +
                    " ( company_code, area_code, point_name, point_addr, temperature, humidity,  storehouse_property, point_status," +
                    " temperature_status,humidity_status, longitude, latitude,battery, signal_strength, task_state, create_time, ly ) " +
                    " values " +
                    " ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'1') ";

            List<Object[]> insertList = new ArrayList();
            for (int i = 0; i < jsonArray.size(); i++) {
                String typeNumber = jsonArray.getJSONObject(i).get("type_number") + "";
                String typeName = "";
                String pointName = "";
                String pointAddr = "";
                String temperature = "";
                String humidity = null;
                String temperature_status = "";
                String humidity_status = "";
                String longitude = "";
                String latitude = "";
                String battery = "";
                String signal_strength = "";
                String task_state = "-1";
                if (StringUtils.isNotEmpty(typeNumber)) {
                    //132 144 149 151 152 161 162 163
                    //主机和终端是否一致
                    EquipmentUniqueBo equipmentUnique = uniqueMap.get(typeNumber);
                    if ("1".equals(equipmentUnique.getIsConsistent())) {
                        pointName = jsonArray.getJSONObject(i).get("type") + "(" + jsonArray.getJSONObject(i).get("measuring_point_addr").toString() + ")"; // 测点名称
                        typeName = jsonArray.getJSONObject(i).get("storehouse_property") + "";
                    } else {
                        pointName = jsonArray.getJSONObject(i).get("type") + "(" + jsonArray.getJSONObject(i).get("measuring_point_addr").toString().substring(0, jsonArray.getJSONObject(i).get("measuring_point_addr").toString().indexOf("-")) + ")"; // 测点名称
                        typeName = "车载";
                    }
                } else {
                    /**
                     * 不返回就找测点中的名字
                     */
                    List<ListOrderedMap> point = Jdbc.find("select measuring_point_name from equipment_config where company_code = '" + companyCode + "' and area_code = '" + areaCode + "' and measuring_point_addr = '" + jsonArray.getJSONObject(i).get("measuring_point_addr") + "' ", new Object[]{});
                    if (point != null && point.size() > 0) {
                        pointName = point.get(0).get("measuring_point_name") + "";
                    } else {
                        pointName = jsonArray.getJSONObject(i).get("measuring_point_addr") + "";
                    }
                }
                if (StringUtils.isNotEmpty(jsonArray.getJSONObject(i).get("measuring_point_addr").toString())) {
                    pointAddr = jsonArray.getJSONObject(i).get("measuring_point_addr") + "";
                }
                String temperature1 = jsonArray.getJSONObject(i).get("temperature").toString();
                if (StringUtils.isNotBlank(temperature1) && !"null".equals(temperature1)) {
                    temperature = jsonArray.getJSONObject(i).get("temperature") + ""; // 温度
                }
                String humidity1 = jsonArray.getJSONObject(i).get("humidity").toString();
                if (StringUtils.isNotBlank(humidity1) && !"null".equals(humidity1)) {
                    humidity = jsonArray.getJSONObject(i).get("humidity") + ""; // 湿度
                }
                if (StringUtils.isNotBlank(jsonArray.getJSONObject(i).get("temperature_status").toString())) {
                    temperature_status = jsonArray.getJSONObject(i).get("temperature_status") + ""; // 温度状态
                }
                if (StringUtils.isNotBlank(jsonArray.getJSONObject(i).get("humidity_status").toString())) {
                    humidity_status = jsonArray.getJSONObject(i).get("humidity_status") + ""; // 温度状态
                }

                if (StringUtils.isNotEmpty(jsonArray.getJSONObject(i).get("longitude").toString())) {
                    longitude = jsonArray.getJSONObject(i).get("longitude") + ""; // 经度
                }
                if (StringUtils.isNotEmpty(jsonArray.getJSONObject(i).get("latitude").toString())) {
                    latitude = jsonArray.getJSONObject(i).get("latitude") + ""; // 温度状态
                }
                if (StringUtils.isNotEmpty(jsonArray.getJSONObject(i).get("battery").toString())) {
                    battery = jsonArray.getJSONObject(i).get("battery") + ""; // 电量
                }
                if (StringUtils.isNotEmpty(jsonArray.getJSONObject(i).get("signal_strength").toString())) {
                    signal_strength = jsonArray.getJSONObject(i).get("signal_strength") + ""; // 信号强度
                }
                if (StringUtils.isNotBlank(jsonArray.getJSONObject(i).get("task_state").toString())) {
                    task_state = jsonArray.getJSONObject(i).get("task_state") + ""; // 任务状态
                }
                Object[] obj = new Object[]{
                        companyCode,
                        areaCode,
                        pointName,
                        pointAddr,
                        temperature,
                        humidity,
                        typeName,
                        0,
                        temperature_status,
                        humidity_status,
                        longitude,
                        latitude,
                        battery,
                        signal_strength,
                        task_state,
                        new Date()
                };
                insertList.add(obj);
            }
            if (insertList.size() > 0) {
                realTime.info("==> 获取到实时数据，执行插入");
                Jdbc.piliang(insertRealTimeSQL, new LqPiLiang() {
                    public void piliang(LqJdbcFactory jdbc) {
                        insertList.forEach(l -> {
                            jdbc.executeS(l);
                        });
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新追踪表（平台）
     *
     * @param companyKey
     * @param recordId
     * @param dataType
     */
    public static void updateTrackPingTai(String companyKey, String recordId, String dataType) {
        logTrack.info("========================================== Start ==========================================");
        logTrack.info("追踪ID值        : " + recordId);
        logTrack.info("数据类型        : " + dataType);
        logTrack.info("企业KEY         : " + companyKey);
        try {
            Jdbc.execute(SqlConstant.SQL_REPLACE_TARK_PINGTAI, new Object[]{recordId, companyKey, dataType, recordId, companyKey, dataType});
        } catch (Exception e) {
            e.printStackTrace();
        }
        logTrack.info("========================================== End   ==========================================" + Constants.LINE_SEPARATOR);
    }

    /**
     * 判断字符串是否为JSON格式
     * @param str 需要判断的字符串
     * @return true:是JSON格式 false:不是JSON格式
     */
    public static boolean isJsonFormat(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        try {
            // 尝试解析为JSONObject
            JSON.parseObject(str);
            return true;
        } catch (Exception e) {
            try {
                // 尝试解析为JSONArray
                JSON.parseArray(str);
                return true;
            } catch (Exception e1) {
                return false;
            }
        }
    }
}
